/*
 * Copyright 2009 Al Phillips.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package xsd4gorm.xsd.parts

import xsd4gorm.exception.XSDTypeNotFoundException

/**
 *
 * @author Al Phillips
 */
public class XSDType {

    private String resolvedType
    private boolean xsdBuiltIn

    public static def types = [
        string:  'String',
        integer: 'int',
        number:  'int',
        positiveInteger: 'int',
        decimal: 'Decimal',
        date:    'Date',
        NMTOKEN: 'String'
    ]

    /**
     *
     * groovy.util.slurpersupport.Attributes type
     */
    public XSDType(def type){
        this.resolvedType = resolveType(type)
        this.xsdBuiltIn = isXSDType(type)
    }

    public boolean isXSDBuiltInType(){
        xsdBuiltIn
    }

    private boolean isXSDType(def type){
        if (type.text().indexOf(':') != -1){
            def prefix = type.text().substring(0, type.text().indexOf(':'))
            def nsUri = type.lookupNamespace(prefix)
            if (nsUri == javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI){
                return true
            }
        }
        return false
    }

    private String resolveType(def type){
        if (type.text().indexOf(':') != -1){
            def prefix = type.text().substring(0, type.text().indexOf(':'))
            def nsUri = type.lookupNamespace(prefix)
            if (nsUri == javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI){
                return type.text().substring(type.text().indexOf(':') + 1)
            }
        }
        return type.text()
    }

    public String getXSDType(){
//        println 'type = ' + resolvedType
//        println 'BuildtInTypes.types = ' + types
        
        if (!types.containsKey(resolvedType)){
            throw new XSDTypeNotFoundException()
        }
        types.get(resolvedType)
    }

}